<template>
  <CustomHeader ref="customHeader" backgroundColor="#dbf5f5"></CustomHeader>

  <view class="job-status-container">
    <!-- 页头部分 -->
    <view class="header">
      <view class="header-left" @tap="goBack">
        <image src="/static/icons/left_arrow.png" class="back-icon"></image>
      </view>
      <view class="header-right"></view>
    </view>

    <!-- 标题部分 -->
    <view class="title-section">
      <text class="main-title">想找什么工作?</text>
      <text class="sub-title">添加多个求职期望，可获得精准工作机会</text>
    </view>

    <!-- 求职期望列表 -->
    <view class="expectation-box">
      <view class="expectation-list">
        <uni-list>
          <uni-list-item
            v-for="(item, index) in expectationList"
            :key="index"
            clickable
            showArrow
            @click="editExpectation(item)"
          >
            <template v-slot:body>
              <view class="expectation-item">
                <view class="expectation-header">
                  <text class="job-name">{{ item.jobName }}</text>
                  <text class="job-city">[{{ item.city }}]</text>
                </view>
                <view class="expectation-footer">
                  <text class="job-salary">{{
                    formatSalary(item.beginSalary, item.endSalary)
                  }}</text>
                  <text class="separator">|</text>
                  <text class="job-industry">{{ item.industry }}</text>
                </view>
              </view>
            </template>
          </uni-list-item>
        </uni-list>
      </view>
      <!-- 添加求职期望按钮 -->
      <view class="add-btn-container">
        <button class="add-btn" @tap="addNewExpectation">
          <image
            src="/static/icons/candidate/add_green.png"
            class="add-icon"
          ></image>
          <text class="add-text">继续添加求职期望</text>
        </button>
      </view>
    </view>

    <!-- 求职状态部分 -->
    <view class="status-section">
      <uni-list>
        <uni-list-item
          v-if="jobSeekStatusList.length === 0"
          showArrow
          clickable
        >
          <template v-slot:body>
            <view class="section-content">
              <text class="empty-text">暂无求职状态</text>
            </view>
          </template>
        </uni-list-item>
        <uni-list-item
          v-else
          showArrow
          clickable
          @click="showStatusPicker"
          title="求职状态"
          :rightText="currentStatusText"
        >
        </uni-list-item>
      </uni-list>
    </view>

    <!-- 求职状态选择器弹窗 -->
    <uni-popup ref="statusPopup" type="bottom">
      <view class="status-popup">
        <view class="popup-header">
          <text class="popup-title">求职状态</text>
          <view class="popup-actions">
            <text class="cancel-btn" @click="closeStatusPopup">取消</text>
            <text class="confirm-btn" @click="confirmStatus">确定</text>
          </view>
        </view>
        <view class="picker-container">
          <picker-view
            :value="tempSelectedIndex"
            @change="onPickerChange"
            class="picker-view"
            indicator-style="height: 100rpx;"
          >
            <picker-view-column>
              <view
                class="picker-item"
                v-for="(item, index) in jobSeekStatusList"
                :key="index"
              >
                <text>{{ item.value }}</text>
              </view>
            </picker-view-column>
          </picker-view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import CustomHeader from "@/components/CustomHeader.vue";
import {
  getDictionary,
  saveJobSeekStatus,
  getMyJobIntention,
} from "@/api/resume.js";
import cacheManager from "@/utils/cache.js";

// 求职期望列表数据（示例数据）
const expectationList = ref([
  {
    id: "1",
    jobName: "前端开发工程师",
    city: "重庆",
    industry: "互联网",
    beginSalary: 8,
    endSalary: 12,
  },
  {
    id: "2",
    jobName: "UI设计师",
    city: "成都",
    industry: "互联网/设计",
    beginSalary: 10,
    endSalary: 15,
  },
]);

// 求职状态字典数据
const jobSeekStatusList = ref([]);
// 当前选中的求职状态索引
const selectedStatusIndex = ref(0);
// 临时选中的求职状态索引（用于弹窗）
const tempSelectedIndex = ref([0]);
// 当前选中的求职状态文本
const currentStatusText = ref("");
// 当前选中的求职状态dataKey
const currentStatusKey = ref("");

const customHeader = ref(null);
const statusPopup = ref(null);

// 缓存键名和过期时间（毫秒）
const CACHE_KEY = "job_seek_status";
const CACHE_EXPIRY = 24 * 60 * 60 * 1000; // 24小时

// 获取缓存的字典数据
const getCachedDictionary = () => {
  try {
    return cacheManager.get(CACHE_KEY);
  } catch (e) {
    console.error("获取缓存字典数据失败:", e);
  }
  return null;
};

// 设置字典数据缓存
const setCachedDictionary = (data) => {
  try {
    cacheManager.set(CACHE_KEY, data, CACHE_EXPIRY);
  } catch (e) {
    console.error("设置缓存字典数据失败:", e);
  }
};

// 获取求职状态字典数据
const fetchJobSeekStatus = async () => {
  try {
    // 先尝试从缓存获取
    const cachedData = getCachedDictionary();
    if (cachedData) {
      jobSeekStatusList.value = cachedData;
      // 设置当前选中的状态
      setSelectedStatus();
      return;
    }

    // 缓存没有则从接口获取
    const data = await getDictionary("job_seek_status");
    if (data && Array.isArray(data)) {
      jobSeekStatusList.value = data;
      // 缓存数据
      setCachedDictionary(data);
      // 设置当前选中的状态
      setSelectedStatus();
    }
  } catch (error) {
    console.log("获取求职状态字典数据失败:", error);
  }
};

// 根据当前状态设置选中项
const setSelectedStatus = () => {
  if (currentStatusKey.value && jobSeekStatusList.value.length > 0) {
    const index = jobSeekStatusList.value.findIndex(
      (item) => item.value === currentStatusKey.value
    );
    if (index !== -1) {
      selectedStatusIndex.value = index;
      tempSelectedIndex.value = [index];
      currentStatusText.value = jobSeekStatusList.value[index].value;
    }
  } else if (jobSeekStatusList.value.length > 0) {
    // 设置默认值
    selectedStatusIndex.value = 0;
    tempSelectedIndex.value = [0];
    currentStatusText.value = jobSeekStatusList.value[0].value;
  }
};

// 获取我的求职意向数据
const fetchMyJobIntention = async () => {
  try {
    // 直接从接口获取数据，不再检查缓存
    const response = await getMyJobIntention();
    if (response) {
      // 设置求职期望列表
      if (response.workExpectList && Array.isArray(response.workExpectList)) {
        expectationList.value = response.workExpectList;
      }

      // 设置当前求职状态
      if (response.status) {
        currentStatusKey.value = response.status;
      }

      return true;
    }
  } catch (error) {
    console.log("获取我的求职意向数据失败:", error);
    uni.showToast({
      title: "获取数据失败",
      icon: "none",
    });
  }
  return false;
};

// 显示求职状态选择器
const showStatusPicker = () => {
  tempSelectedIndex.value = [selectedStatusIndex.value];
  statusPopup.value.open();
};

// 关闭求职状态选择器
const closeStatusPopup = () => {
  statusPopup.value.close();
};

// 选择器变化事件
const onPickerChange = (e) => {
  tempSelectedIndex.value = e.detail.value;
};

// 确认选择求职状态
const confirmStatus = async () => {
  const index = tempSelectedIndex.value[0];
  selectedStatusIndex.value = index;
  const newStatus = jobSeekStatusList.value[index].value; // 改为使用value而不是dataKey
  currentStatusText.value = jobSeekStatusList.value[index].value;

  try {
    // 保存到服务器
    await saveJobSeekStatus(newStatus);
    console.log("求职状态已更新并保存:", newStatus);
    uni.showToast({
      title: "求职状态已更新",
      icon: "success",
    });
    // 更新当前状态key
    currentStatusKey.value = jobSeekStatusList.value[index].dataKey; // 保持dataKey用于匹配
    // 关闭弹窗
    closeStatusPopup();
  } catch (error) {
    console.log("保存求职状态失败:", error);
    uni.showToast({
      title: "保存失败，请重试",
      icon: "none",
    });
  }
};

// 格式化薪资显示
const formatSalary = (begin, end) => {
  if (begin && end) {
    return `${begin}-${end}K`;
  }
  return "面议";
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 编辑求职期望
const editExpectation = (item) => {
  console.log("编辑求职期望:", item);
  uni.navigateTo({
    url: `/pages/candidate/resume/addWorkExpectation?id=${item.id}`,
  });
};

// 添加新的求职期望
const addNewExpectation = () => {
  console.log("添加新的求职期望");
  uni.navigateTo({
    url: "/pages/candidate/resume/addWorkExpectation",
  });
};

// 页面加载时获取数据
onMounted(() => {
  console.log("页面加载，开始获取数据");
  // 获取我的求职意向数据
  fetchMyJobIntention().then((hasCachedData) => {
    // 如果没有缓存数据或缓存已过期，需要从接口获取数据后再获取字典数据
    // 如果有缓存数据，也需要获取字典数据来匹配状态
    fetchJobSeekStatus();
  });
});
</script>

<style scoped>
.job-status-container {
  min-height: 100vh;
  background: linear-gradient(to bottom, #dbf5f5, #ffffff);
  padding-bottom: 40rpx;
}

/* 页头样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background-color: #dbf5f5;
  padding: 0 30rpx;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
  width: 60rpx;
}

.back-icon {
  width: 32rpx;
  height: 32rpx;
}

.header-title {
  font-size: 34rpx;
  font-weight: 500;
  color: #333333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.header-right {
  width: 60rpx;
}

/* 标题部分样式 */
.title-section {
  padding: 40rpx 30rpx;
  background-color: #ffffff;
  background: linear-gradient(to bottom, #dbf5f5, #f2f8fb);
}

.main-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #333333;
  display: block;
  margin-bottom: 20rpx;
}

.sub-title {
  font-size: 26rpx;
  color: #999999;
}

/* 求职期望列表样式 */
.expectation-list {
  margin-top: 5rpx;
}

.expectation-item {
  padding: 20rpx 0;
}

.expectation-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.job-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-right: 10rpx;
}

.job-city {
  font-size: 28rpx;
  color: #666666;
}

.expectation-footer {
  display: flex;
  align-items: center;
}

.job-salary {
  font-size: 28rpx;
  color: #ff6b35;
}

.separator {
  margin: 0 10rpx;
  color: #d0d0d0;
}

.job-industry {
  font-size: 28rpx;
  color: #666666;
}

/* 添加按钮样式 */
.add-btn-container {
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  border-radius: 8rpx;
  border: 2rpx dashed #00bdb4;
  background-color: #ffffff;
  padding: 0;
}

.add-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 10rpx;
}

.add-text {
  font-size: 30rpx;
  color: #00bdb4;
}

/* 求职状态部分样式 */
.status-section {
  padding: 15rpx;
  margin: 0 10rpx 10rpx 10rpx;

  border-radius: 20rpx;
  background-color: #ffffff;
}

.section-title {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.title-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.status-info {
  display: flex;
  flex-direction: column;
}

.status-name {
  font-size: 30rpx;
  color: #333333;
  margin-bottom: 5rpx;
}

.status-desc {
  font-size: 24rpx;
  color: #999999;
}

:deep(.uni-list--border-top) {
  display: none !important;
}

:deep(.uni-list--border-bottom) {
  display: none !important;
}

:deep(.uni-border-top-bottom) {
  border: none !important;
}
:deep(.uni-list--border) {
  display: none;
}

.expectation-box {
  padding: 10px;
  margin: 0 15rpx 15rpx 15rpx;
  border-radius: 50rpx;
  background-color: #fff;
}

/* 求职状态选择弹出层样式 */
.status-popup {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx 30rpx;
  min-height: 400rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1a1a1a;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

.popup-actions {
  display: flex;
  gap: 30rpx;
}

.cancel-btn {
  font-size: 32rpx;
  color: #999;
  font-weight: 400;
  cursor: pointer;
}

.confirm-btn {
  font-size: 32rpx;
  color: #00bdb4;
  font-weight: 500;
  cursor: pointer;
}

.picker-container {
  height: 300rpx;
  width: 100%;
  overflow: hidden;
}

.picker-view {
  height: 100%;
  width: 100%;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100rpx;
  line-height: 100rpx;
  font-size: 32rpx;
  color: #333;
}

.status-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 400;
  line-height: 1.5;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

:deep(.uni-list-item__content-title) {
  font-size: 30rpx;
  font-weight: 500;
}
:deep(.uni-list-item__extra-text) {
  font-size: 30rpx !important;
}
</style>